package com.system.demo.service.rabbitmq;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.system.demo.commonService.MailService;
import com.system.demo.entity.database.UserNotifications;
import com.system.demo.entity.database.User;
import com.system.demo.mapper.UserMapper;
import com.system.demo.mapper.UserNotificationsMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.Map;

import static com.system.demo.service.constant.MailConstant.NOTIFICATION_TEMPLATE;

@Service
public class NotificationConsumer {

    @Autowired
    private UserNotificationsMapper notificationsMapper; // MySQL 数据库接口

    @Autowired
    private UserMapper userMapper; // 用于查找用户邮箱

    @Autowired
    private MailService mailService; // 邮件服务

    @Autowired
    private ObjectMapper objectMapper; // Jackson ObjectMapper，用于JSON转对象

    // 监听队列，接收通知
    @RabbitListener(queues = "notificationQueue")
    public void receiveNotification(String message) {
        try {
            // 将接收到的 JSON 字符串转换为 UserNotifications 对象
            UserNotifications notification = objectMapper.readValue(message, UserNotifications.class);

            // 存储通知到数据库
            notificationsMapper.insert(notification);

            // 查找用户邮箱
            User user = userMapper.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<User>()
                            .eq("uid", notification.getUid())
            );

            if (user == null || user.getMail() == null) {
                System.out.println("用户未设置邮箱，无法发送邮件通知");
                return;
            }

            // 构建邮件内容
            Map<String, Object> variables = new HashMap<>();
            variables.put("message", notification.getContent());

            // 发送邮件
            mailService.sendMail(
                    user.getMail(),
                    "系统通知", // 邮件主题
                    NOTIFICATION_TEMPLATE, // 邮件模板路径
                    variables
            );

            System.out.println("通知邮件已发送给用户：" + user.getUid());
        } catch (MessagingException e) {
            // 邮件发送失败日志
            System.err.println("邮件发送失败：" + e.getMessage());
        } catch (Exception e) {
            // 通用异常日志
            System.err.println("消息处理失败：" + e.getMessage());
        }
    }
}
